package boxync;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;

public class FileHelper {
    public static int DOWNLOAD_UNIT = 4096;
    
    public static byte[][] splitFile(File f) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream(f);
        int size = 4096;
        int chunk = (int) (f.length()/size) + 1;
        byte[][] value = new byte[chunk][];
        int i = 0;
        int it = 0;
        int rem = (int) (f.length() % size); 
        while (it < chunk) {
            try {
                if (it!=chunk-1) {
                    byte[] tmp = new byte[size];
                    i = fis.read(tmp, 0, size);
                    value[it] = tmp;
                } else {
                    byte[] tmp = new byte[rem];
                    i = fis.read(tmp, 0, rem);
                    value[it] = tmp;
                }
                
                it++;
            } catch (IOException ex) {
                Logger.getLogger(FileHelper.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
        return value;
    }
    
    public static void writeByteToFile(byte[][] b, File f) {
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream(f);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileHelper.class.getName()).log(Level.SEVERE, null, ex);
        }
        for (int i = 0; i < b.length; i++) {
            try {
                fos.write(b[i]);
            } catch (IOException ex) {
                Logger.getLogger(FileHelper.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    /**
     * Menulis array of string yg merupakan byte-byte file sebagai file baru di path.
     * @param bytes Array of string dari byte file
     * @param path Tujuan penulisan file
     * @param time 
     * @throws IOException  
     */
    public static void writeStringToFile(String bytes, String path, String time) throws IOException {
        File f = new File(path);
        FileUtils.writeStringToFile(f, bytes);
        f.setLastModified(new Date(FileInfo.getYear(time) - 1900, FileInfo.getMonth(time) - 1,
                FileInfo.getDate(time), FileInfo.getHour(time), FileInfo.getMinute(time),
                FileInfo.getSecond(time)).getTime());
    }
    
    public static void writeStringsToFile(ArrayList<String> bytes, String path) throws IOException{
        StringBuilder sb = new StringBuilder();
        for (String b : bytes) {
            sb.append(b);
        }
        FileUtils.writeStringToFile(new File(path), sb.toString());
    }
    
    public static void writeBytesToFile(byte[] bytes, String path, String time) throws IOException {
        File f = new File(path);
        FileUtils.writeByteArrayToFile(f, bytes);
        f.setLastModified(new Date(FileInfo.getYear(time) - 1900, FileInfo.getMonth(time) - 1,
                FileInfo.getDate(time), FileInfo.getHour(time), FileInfo.getMinute(time),
                FileInfo.getSecond(time)).getTime());
    }
    
    public static byte[] readFileToBytes(String path) throws IOException {
        return FileUtils.readFileToByteArray(new File(path));
    }
    
    
    /**
     * Membaca file dan mengembalikan array of string yg merupakan bytes hasil pembacaan file.
     * @param path Path file berada
     * @return Array of string dari byte-byte file
     * @throws IOException 
     * 
     */
    public static String readFileToString(String path) throws IOException {    
        return FileUtils.readFileToString(new File(path));
    }
    
    public static String[] readFileToStrings(String path) throws IOException {
        return FileUtils.readFileToString(new File(path)).split("\n");
    }
    
    /**
     * Membaca deleted log dari file di path dan mengembalikan ArrayList<FileInfo>.
     * @param dir 
     * @param userPath 
     */
    public static void readDeletedLog(BoxyncDir dir) {
        File del = new File(dir.file + "/__deleted.txt");
        if (!del.exists())
            return;
        
        try {
            List<String> strings = FileUtils.readLines(del);
            for (String s : strings) {
                dir.insertFile(s, dir.file + FileInfo.getFileName(s));
            }
        } catch (IOException e) {
            System.out.println("IOExc in FileHelper.readDeletedLog()");
        }
    }
    
    
    /**
     * Menulis ulang file deleted log dengan tambahan BoxyncFile del baru. Digunakan oleh Server.
     * @param dir 
     */
    public static void writeDeletedLog(BoxyncDir dir) {
        StringBuilder sb = new StringBuilder();
        ArrayList<FileInfo> dels = dir.getDeletedList();
        for (FileInfo f : dels) {
            sb.append(f.toString()).append("\n");
        }
        if (sb.length() > 0)
            sb.deleteCharAt(sb.length() - 1);
        
        try {
            FileUtils.writeStringToFile(new File(dir.file+"/__deleted.txt"), sb.toString());
        } catch (IOException e) {
            System.err.println("IOExc in FileHelper.writeDeletedLog()");
        }
    }
    
    public static void setTimeStamp(String path, String time) {
        File f = new File(path);
        Date d = new Date(FileInfo.getYear(time), FileInfo.getMonth(time), 
                FileInfo.getDate(time), FileInfo.getHour(time), 
                FileInfo.getMinute(time), FileInfo.getSecond(time));
        f.setLastModified(d.getTime()/1000);
    }
    
    public static void main(String[] args) {
        try {
            FileUtils.moveDirectoryToDirectory(new File("D:/boxync/wibi"), new File("D:/wibi"), true);
        } catch (IOException e) {}
    }
}